import cv2
import numpy as np
from PyQt5.QtCore import QThread, pyqtSlot, QVariant, Qt, pyqtSignal
from PyQt5.QtGui import QImage
from PyQt5 import QtGui
from camera_thread import CameraThread


class HSVSearch(CameraThread):

    def __init__(self, parent=None, camera=0):
        super().__init__(parent=parent, camera=camera)
        self.hl = 0
        self.hh = 255
        self.sl = 0
        self.sh = 255
        self.vl = 0
        self.vh = 255

        self.color_table = []
        for i in range(256):
            self.color_table.append(QtGui.qRgb(i, i, i))

    @ pyqtSlot(QVariant)
    def update_hsv(self, hsv_list):
        li = hsv_list
        self.hl = li[0]
        self.hh = li[1]
        self.sl = li[2]
        self.sh = li[3]
        self.vl = li[4]
        self.vh = li[5]

    def process_image(self, frame):
        lower = np.array([self.hl, self.sl, self.vl], dtype=np.uint8)
        upper = np.array([self.hh, self.sh, self.vh], dtype=np.uint8)
        return cv2.inRange(frame, lower, upper)

    def send_image_to_gui(self, frame):
        h, w = frame.shape
        convertToQtFormat = QImage(frame.data, w, h,  QImage.Format_Indexed8)
        convertToQtFormat.setColorTable(self.color_table)
        self.changePixmap.emit(convertToQtFormat)
